import { hasPayServiceApi } from '@/api/Plan';
import { pageOpeTypeEnum } from '@/common';
import CusDrawer from '@/components/CusDrawer';
import CourseWareDetail from '@/components/resourceLibraryComp/CourseWareDetail';
import ResourceNameForTable from '@/components/resourceLibraryComp/ResourceNameForTable';
import TestPaperDetail from '@/components/resourceLibraryComp/TestPaperDetail';
import YmCollaPanes from '@/components/YmCollaPanes';
import { useAppSelector } from '@/redux/store';
import { DeleteOutlined, DragOutlined } from '@ant-design/icons';
import { App, Button, Empty } from 'antd';
import { isEmpty } from 'lodash-es';
import React, { useId, useMemo, useState } from 'react';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { useNavigate } from 'react-router-dom';
import OStyle from './index.less';
import { EStudyPackageResourceNameType, EStudyPackageResourceType, StudyPackageProps } from './interface';

const DRAWERWIDTH = 680;

const StudyPackage: React.FC<StudyPackageProps> = (props) => {
  const {
    message,
    modal: { confirm },
  } = App.useApp();
  const navigator = useNavigate();
  const { entId, organizationType } = useAppSelector((state) => state.loginEnt); //organizationType 1:协会，0：企业
  const { loginRole } = useAppSelector((state) => state.loginUser);
  const dragAndDropKey = useId();
  const { value, onChange } = props;
  const [collPanesActiveKeys, setCollPanesActiveKeys] = useState<string[]>([]);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [currRowResourceId, setCurrRowResourceId] = useState<string>();
  const [currType, setCurrType] = useState<string>(); // '100':视频课件， '200':图文课件， '300':试卷， '400':pdf课件
  const [currResourceType, setCurrResourceType] = useState<string>(); // '100':企业协会自建 ，200：平台
  const [hasPayService, setHasPayService] = useState(false); //是否购买安学行服务
  const [currIsCharge, setCurrIsCharge] = useState<number>();
  // 添加的时候默认不展开，不然moveCard--onChange(value)--又会全部展开
  // useEffect(() => {
  //   const keys: string[] = value?.map((item) => item.id) || [];
  //   setCollPanesActiveKeys(keys);
  // }, [value]);

  // 删除当前学习包
  const deleteCurStudyPackage = (index: number, id: string) => {
    value!.splice(index, 1);
    onChange?.([...value!]);
    const newCollPanesActiveKeys = collPanesActiveKeys.filter((key: string) => key !== id);
    setCollPanesActiveKeys(newCollPanesActiveKeys);
  };

  //课件详情drawer 配置
  // 该详情也要区分 是boss 还是 企业/协会
  const drawerConfig = useMemo(() => {
    if (!currRowResourceId || !currType) return;
    let DrawerChild, title;
    if (currType === '300') {
      title = '试卷详情';
      DrawerChild = (
        <TestPaperDetail
          coursewareId={currRowResourceId}
          resourceType={currResourceType}
          hasPayService={hasPayService}
          isCharge={currIsCharge || 0}
        />
      );
    } else {
      title = '课件详情'; // "f51e9ab1975440a4a964d1a6915efb4f"
      DrawerChild = <CourseWareDetail coursewareId={currRowResourceId} resourceType={currResourceType} />;
    }
    return {
      title,
      width: DRAWERWIDTH,
      open: drawerOpen,
      onClose: () => {
        setDrawerOpen(false);
      },
      destroyOnClose: true,
      children: DrawerChild,
    };
  }, [currRowResourceId, drawerOpen, currType, currResourceType, hasPayService, currIsCharge]);

  // 打开详情抽屉
  //organizationType === 0(企业) && sourceType === '200' 平台课件包试卷才会收费, 判断是否购买学习位
  const openCourseWareDrawer = (item: any, sItem: any) => {
    function _operation(isChargeParam: number) {
      const { coursewareId, type, sourceType } = sItem;
      setCurrRowResourceId(coursewareId);
      setCurrType(type);
      setCurrResourceType(sourceType);
      setCurrIsCharge(isChargeParam);
      setDrawerOpen(true);
    }

    const { isCharge } = item;
    if (isCharge && organizationType === 0 && sItem.sourceType === '200') {
      if (entId && isCharge) {
        //当前企业是否购买学习位
        hasPayServiceApi({ entId })
          .then((res) => {
            // console.log('--hasPayService--res--:', res);
            if (res.code === '200') {
              const tempData = !!res.data; // 1:true,0:false
              setHasPayService(tempData);

              if (sItem.type === '300') {
                //试卷
                _operation(1);
              } else if (!tempData) {
                confirm({
                  title: '提示',
                  content: '企业还未购买安学行学习位，无法查看收费内容，请前往购买安学行学习位！',
                  centered: true,
                  okText: '前往',
                  onOk: () => {
                    if (loginRole == '1' || loginRole == '0') {
                      navigator('/safeService/buyService');
                    } else {
                      message.warning('您暂无权限，请联系企业管理人员！');
                    }
                  },
                });
              }
            }
          })
          .catch((err) => {
            console.log('--TestPaperDetail--hasPayServiceApi--err--:', err);
          });
      }
    } else {
      _operation(0);
    }
  };

  return (
    <>
      <CusDrawer {...drawerConfig} />
      {isEmpty(value) ? (
        <Empty style={{ marginBottom: '16px' }} />
      ) : (
        <DndProvider backend={HTML5Backend}>
          {value!.map((item, index) => (
            <YmCollaPanes
              key={item.id}
              collPanesActiveKeys={collPanesActiveKeys}
              onSetCollPanesActiveKeys={(activeKeys) => {
                setCollPanesActiveKeys(activeKeys);
              }}
              paneKey={item.id!}
              headerTitle={`学习包${index + 1}`}
              contentClass={OStyle.cus_item_content}
              extra={
                <p className={OStyle.pane_extra}>
                  <DragOutlined style={{ cursor: 'move' }} />
                  <DeleteOutlined
                    onClick={() => {
                      deleteCurStudyPackage(index, item.id!);
                    }}
                  />
                </p>
              }
              dragAndDropParams={{
                index,
                onCardMove: (a, b) => {
                  const nextValue = value!.slice();
                  const temp = nextValue[a];
                  nextValue[a] = nextValue[b];
                  nextValue[b] = temp;
                  onChange?.(nextValue);
                },
                dragAndDropKey,
              }}
            >
              <ul className={OStyle.package_content_list}>
                {item.studyList.map((sItem, sIndex) => (
                  <li className={OStyle.list_item} key={sItem.coursewareId}>
                    <ResourceNameForTable
                      title={sItem.name}
                      resourceType={0}
                      resourceFrom={EStudyPackageResourceType[Number(sItem.type)] as any}
                    />
                    <p className={OStyle.item_right}>
                      <span className={OStyle.right_text}>{EStudyPackageResourceNameType[Number(sItem.type)]}</span>
                      {item.pageType !== pageOpeTypeEnum['edit'] && (
                        <Button
                          type="text"
                          size="small"
                          onClick={(e: React.MouseEvent) => {
                            e.stopPropagation();
                            openCourseWareDrawer(item, sItem);
                          }}
                        >
                          <span className="safe-edu_table_operation_text">详情</span>
                        </Button>
                      )}
                    </p>
                  </li>
                ))}
              </ul>
            </YmCollaPanes>
          ))}
        </DndProvider>
      )}
    </>
  );
};

export default StudyPackage;
